/**
 *
 */
package com.jdy.haoduoaiteacher.fragment;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.annotation.AnyRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.jdy.haoduoai.model.StudentInfoxxj;
import com.jdy.haoduoaiteacher.FileUtils;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.activity.BaseActivity;
import com.jdy.haoduoaiteacher.activity.WebViewContainerActivity;
import com.jdy.haoduoaiteacher.adapter.ChatWallPaperAapter;
import com.jdy.haoduoaiteacher.adapter.ListDevicesAdapter;
import com.jdy.haoduoaiteacher.adapter.SpeakForYouItem;
import com.jdy.haoduoaiteacher.adapter.SpeakWordHistoryAdapter;
import com.jdy.haoduoaiteacher.adapter.VoicePlayClickListener;
import com.jdy.haoduoaiteacher.audioconverter.AndroidAudioConverter;
import com.jdy.haoduoaiteacher.audioconverter.callback.IConvertCallback;
import com.jdy.haoduoaiteacher.audioconverter.model.AudioFormat;
import com.jdy.haoduoaiteacher.enums.MediaType;
import com.jdy.haoduoaiteacher.enums.PlayState;
import com.jdy.haoduoaiteacher.enums.PosterType;
import com.jdy.haoduoaiteacher.enums.SendState;
import com.jdy.haoduoaiteacher.enums.SpeakForYouType;
import com.jdy.haoduoaiteacher.event.OnMediaResendEvent;
import com.jdy.haoduoaiteacher.event.OnTextSelectEvent;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.intface.IMParseListener;
import com.jdy.haoduoaiteacher.intface.OnRecommendItemClickListener;
import com.jdy.haoduoaiteacher.intface.PhotoSourceDelegate;
import com.jdy.haoduoaiteacher.model.AlbumCollectionItem;
import com.jdy.haoduoaiteacher.model.AlbumItem;
import com.jdy.haoduoaiteacher.model.ChatType;
import com.jdy.haoduoaiteacher.model.LeMachine;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.SpeakFouYouRecordItem;
import com.jdy.haoduoaiteacher.model.StudentDeviceModel;
import com.jdy.haoduoaiteacher.model.TipWordCategoryItem;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.socket.DeviceStateListener;
import com.jdy.haoduoaiteacher.socket.SocketThreadManager;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.DateUtils;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.LePreference;
import com.jdy.haoduoaiteacher.util.LeXiaoXiaoBanLog;
import com.jdy.haoduoaiteacher.util.OnDataReceivedListener;
import com.jdy.haoduoaiteacher.util.PathUtil;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.util.VoiceRecorder;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;

import org.droidparts.annotation.inject.InjectView;
import org.droidparts.widget.ClearableEditText;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static org.droidparts.Injector.getApplicationContext;

@SuppressLint("InlinedApi")
public class TabMonitorFragment extends BaseFragment implements
        OnClickListener, OnDataReceivedListener, DeviceStateListener, OnRefreshListener, IMParseListener, VoicePlayClickListener.VoiceClickListener {

    private static final String TAG = TabMonitorFragment.class.getSimpleName();

    @InjectView(id = R.id.text_category_layout)
    private LinearLayout mHLayout;
    @InjectView(id = R.id.text_selection_viewpager)
    private android.support.v4.view.ViewPager mTagsViewPager;
    @InjectView(id = R.id.radiogroup)
    private RadioGroup mViewPagerIndicators;
    @InjectView(id = R.id.radio_img, click = true)
    private ImageView mRadioImg;
    @InjectView(id = R.id.ime_img, click = true)
    private ImageView mImeImg;
    @InjectView(id = R.id.img_voice, click = true)
    private ImageView mImg_voice;
    @InjectView(id = R.id.chat_bg_img, click = true)
    private ImageView mChatBgImg;
    @InjectView(id = R.id.bottom_hs)
    private HorizontalScrollView bottomHS;
    @InjectView(id = R.id.recommend_pager)
    private android.support.v4.view.ViewPager mRecommendVp;
    @InjectView(id = R.id.recommend_indicator_rg)
    private RadioGroup mCircleRg;
    @InjectView(id = R.id.btn_tospeak, click = true)
    private Button btn_tospeak;

    @InjectView(id = R.id.txt_to_send_edittext)
    private ClearableEditText mTxt2SendEtx;
    @InjectView(id = R.id.center_layout)
    private RelativeLayout mCenterLayout;
    @InjectView(id = R.id.ask_layout)
    private View ask_layout;
    @InjectView(id = R.id.speak_root_layout)
    private RelativeLayout mRootLayout;
    @InjectView(id = R.id.input_selection_layout)
    private RelativeLayout mInputSelectionLayout;
    @InjectView(id = R.id.ask_search_tv, click = true)
    private TextView mAskSearchTv;
    @InjectView(id = R.id.history_record_listview)
    private ListView mHistoryLV;
    @InjectView(id = R.id.listview_devices)
    private ListView listview_devices;
    @InjectView(id = R.id.refresh_layout)
    private SwipeRefreshLayout mSwipeRefreshLayout;
    @InjectView(id = R.id.change_bg_img)
    private ImageView mChangeBgImg;
    @InjectView(id = R.id.bg_select_gv)
    private GridView mBgSelectGv;

    private ListDevicesAdapter mStoryAdapter;
    private LeUser mLeUser;
    private LayoutInflater mInflater;
    private List<Integer> rbIds;
    private List<Integer> recommend_rbIds;
    private List<SpeakForYouItem> historyWordList;
    private SpeakWordHistoryAdapter sha;
    private int selectedTextViewId = -1;
    private ColorStateList oldColors;
    private List<TextView> categoryTextViewList;
    private int mLastPage = 1;
    private List<TipWordCategoryItem> tipWordList;
    private SparseArray<List<TipWordCategoryItem>> tipWordListSpArray = new SparseArray<List<TipWordCategoryItem>>();
    int tipIndex = 0;
    private String userclass;
    private String account;
    private String classname;

    @Override
    public void onVoiceClicked() {
        loadUnreadMsg();
    }

    private enum ResourceType {
        None, Text, Video, Background, Voice,
    }

    @InjectView(id = R.id.mic_image, click = true)
    private ImageView micImage;
    @InjectView(id = R.id.recording_hint)
    private TextView recordingHint;
    @InjectView(id = R.id.seconds_left_hint)
    private TextView secondsLeftHint;
    @InjectView(id = R.id.recording_container)
    private RelativeLayout recordingContainer;

    private Drawable[] micImages;

    private VoiceRecorder mVoiceRecorder;

    private Uri mResultURI;
    private String mAvatarPath;

    private static final int PHOTO_PICKED_WITH_DATA = 1001;// 相册
    private static final int CAMERA_WITH_DATA = 1002;// 相机
    private static final int CROP_PHOTO = 101;
    private static final File PHOTO_DIR = new File(
            Environment.getExternalStorageDirectory() + "/CameraCache");
    private File mCurrentPhotoFile;// 照相机拍照得到的图片
    private File mCacheFile;
    private static String fileName;
    private RecommendPagerAdapter mRecommendPagerAdapter;
    private String mChatBgPath;
    private int mListViewColor;

    public ArrayList<StudentDeviceModel> mStudentDeviceModelList;
    private String machine_ids = "";
    private View headdd, view_rr;
    private TextView tv_msgnumAll;
    private int mSelectPostion = 0;
    private boolean hasLoad;


    public void jumpToSpeakListAccordMacId(String macId) {
        if (Tools.isEmpty(macId) || mStudentDeviceModelList == null || mStudentDeviceModelList.isEmpty()) {
            return;
        }

        mSelectPostion = 1;

        for (int i = 0; i < mStudentDeviceModelList.size(); i++) {
            if (mStudentDeviceModelList.get(i).machine_id.equalsIgnoreCase(macId)) {
                mSelectPostion = (i + 1);
                break;
            }
        }

        // mSelectPostion = 1;
        mLastPage = 1;
        if (historyWordList != null) {
            historyWordList.clear();
        }
        getHistoryRecords();
        if (mSelectPostion >= 1) {
            // CommonUtil.showToask(getActivity(), position + "号");
            mStoryAdapter.setHighLightPosition(mSelectPostion - 1);
            view_rr.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
        } else {
            mStoryAdapter.setHighLightPosition(-1);
            view_rr.setBackgroundColor(0xffd7d7d7);
        }

        loadUnreadMsg();
    }


    /**
     * 获取绑定设备的方法
     */
    private void getBindDevices() {

        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity,
                                      ResponseResult result) {
                try {
                    if (result.isSuccess()) {
                        if (Tools.isNotNullStr(result.data)) {

                            Log.i("test", "获取到的数据是:" + result.data);

                            List<StudentInfoxxj.DataBean> list = GsonUtil.jsonToList(result.data, StudentInfoxxj.DataBean[].class);

                            mStudentDeviceModelList = new ArrayList<>();

                            if(list!=null && list.size()!=0){


                            for (int i = 0; i < list.size(); i++) {
                                StudentDeviceModel sdm = new StudentDeviceModel();
                                sdm.created_at = list.get(i).getCreated_at();
                                sdm.isChecked = false;
                                sdm.machine_id = list.get(i).getId();
                                sdm.nick_name = list.get(i).getName();
                                sdm.machine = new LeMachine();
                                sdm.machine.avatar = list.get(i).getApp_icon();
                                mStudentDeviceModelList.add(sdm);
                            }
                            }else{
                                if (mStoryAdapter == null) {
                                    mStoryAdapter = new ListDevicesAdapter(getActivity(), mStudentDeviceModelList);
                                    listview_devices.setAdapter(mStoryAdapter);
                                } else {
                                    mStoryAdapter.updateData(mStudentDeviceModelList);
                                }
                            }

                            if (null != mStudentDeviceModelList && mStudentDeviceModelList.size() != 0 && !mStudentDeviceModelList.isEmpty()) {
                                for (StudentDeviceModel item : mStudentDeviceModelList) {
                                    machine_ids += item.machine_id;
                                    machine_ids += ",";
                                }

                                if (Tools.isNotEmpty(machine_ids)) {
                                    machine_ids = machine_ids.substring(0, machine_ids.length() - 1);
                                }

                                if (mStoryAdapter == null) {
                                    mStoryAdapter = new ListDevicesAdapter(getActivity(), mStudentDeviceModelList);
                                    listview_devices.setAdapter(mStoryAdapter);
                                } else {
                                    mStoryAdapter.updateData(mStudentDeviceModelList);
                                }


                                if (headdd == null) {
                                    LayoutInflater inflater = (LayoutInflater) getActivity()
                                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                    headdd = inflater.inflate(R.layout.listdevice_head, null);
                                    headdd.setLayoutParams(new LayoutParams(Tools.getPixelByDip(getApplicationContext(), 70), Tools.getPixelByDip(getApplicationContext(), 80)));
                                }

                                view_rr = headdd.findViewById(R.id.view_rr);
                                tv_msgnumAll = (TextView) headdd.findViewById(R.id.tv_msgnum);

                                if (!hasLoad) {
                                    loadUnreadMsg();
                                    getDeviceOnlineOfflineStatus();
                                    view_rr.setBackgroundColor(0xffd7d7d7);
                                    hasLoad = true;
                                }

                                if (listview_devices.getHeaderViewsCount() > 0 && headdd != null) {
                                    listview_devices.removeHeaderView(headdd);
                                }
                                listview_devices.addHeaderView(headdd);
                                listview_devices.setOnItemClickListener(new OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                        mSelectPostion = position;
                                        mLastPage = 1;
                                        if (historyWordList != null) {
                                            historyWordList.clear();
                                        }
                                        getHistoryRecords();
                                        if (position >= 1) {
                                            // CommonUtil.showToask(getActivity(), position + "号");
                                            mStoryAdapter.setHighLightPosition(position - 1);
                                            view_rr.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
                                        } else {
                                            mStoryAdapter.setHighLightPosition(-1);
                                            view_rr.setBackgroundColor(0xffd7d7d7);
                                        }

                                        loadUnreadMsg();
                                    }
                                });
                                Tools.setListViewHeightBasedOnChildren(listview_devices);
                                mStoryAdapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        if (Tools.isNotNullStr(result.data)) {
                            Toast.makeText(getActivity(), result.data,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<>();
                param_.put("type", "1");
                param_.put("c", account);
                param_.put("role", "2");
                param_.put("userclass", userclass);
                param_.put("platform", "2");
                return HttpUtils.startRequest(com.ycsj.goldmedalnewconcept.constant.Constant.SERVER_URL
                                + "YcsjApiMsg", param_,
                        HttpUtils.TAG_POST_REQUEST);
            }
        }).execute();
    }

    @SuppressLint("ValidFragment")
    public TabMonitorFragment(BaseActivity ba) {
    }

    public TabMonitorFragment() {
    }

    @Override
    public View onCreateView(Bundle savedInstanceState, LayoutInflater inflater,
                             ViewGroup container) {
        View bodyView = LayoutInflater.from(mContext).inflate(
                R.layout.speak_for_u_teacher, container, false);
        return bodyView;
    }

    private HashMap<String, String> mDeviceStatusMap = new HashMap<String, String>();
    private HashMap<String, Integer> mUnreadMsgMap = new HashMap<String, Integer>();

    private void getDeviceOnlineOfflineStatus() {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @SuppressWarnings("unchecked")
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    try {
                        JSONObject jsonObject_AA = new JSONObject(result.data);
                        if (jsonObject_AA != null) {
                            Iterator it_color = jsonObject_AA.keys();
                            while (it_color.hasNext()) {
                                String key = it_color.next().toString();
                                String value = jsonObject_AA.getString(key);
                                mDeviceStatusMap.put(key, value);
                            }
                        }

                        if (mStoryAdapter != null) {
                            mStoryAdapter.mDeviceStatusMap = mDeviceStatusMap;
                            mStoryAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/teacher/check_machine_status", param_,
                        HttpUtils.TAG_POST_REQUEST);

            }
        }).execute();
    }

    private Handler mHandler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            getDeviceOnlineOfflineStatus();
            mHandler.postDelayed(this, 15000);
        }
    };

    private void loadUnreadMsg() {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @SuppressWarnings("unchecked")
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    try {
                        JSONObject jsonObject_AA = new JSONObject(result.data);
                        if (jsonObject_AA != null) {
                            Iterator it_color = jsonObject_AA.keys();
                            while (it_color.hasNext()) {
                                String key = it_color.next().toString();
                                int value = jsonObject_AA.getInt(key);
                                mUnreadMsgMap.put(key, value);
                            }
                        }

                        if (tv_msgnumAll != null) {
                            if (mUnreadMsgMap != null && mUnreadMsgMap.containsKey("all")) {
                                tv_msgnumAll.setText("" + mUnreadMsgMap.get("all"));
                                tv_msgnumAll.setVisibility(View.VISIBLE);
                            } else {
                                tv_msgnumAll.setText("");
                                tv_msgnumAll.setVisibility(View.GONE);
                            }
                        }

                        if (mStoryAdapter != null) {
                            mStoryAdapter.mUnreadMsgMap = mUnreadMsgMap;
                            mStoryAdapter.notifyDataSetChanged();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/teacher/history/unread", param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mAvatarPath = PathUtil.getSpeakForYouWallpaperPath(getApplicationContext());
        init();
        EventBus.getDefault().register(this);
        buildCircles();
        mCircleRg.check(recommend_rbIds.get(0));
        mHandler.postDelayed(runnable, 15000);

        SocketThreadManager.getInstance().setDataReceivedListener(TabMonitorFragment.this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mListViewColor = LePreference.getInstance().getInt(
                "speak_for_you_listview_bg_color", Color.parseColor("#f1f1f1"));

        mChatBgPath = LePreference.getInstance().getString(
                "speak_for_you_wallpaper");

        Uri tmpUri = null;
        if (Tools.isNotEmpty(mChatBgPath))
            tmpUri = Uri.parse(mChatBgPath);
        if (sha == null) {
            sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
        }
        if (sha != null) {
            sha.udpateImagePath();
        }
        setChatBgWallpaper(mListViewColor, tmpUri);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (wakeLock.isHeld())
            wakeLock.release();

        LePreference.getInstance().save("speak_for_you_listview_bg_color",
                mListViewColor);
        LePreference.getInstance().save("speak_for_you_wallpaper", mChatBgPath);

        if (VoicePlayClickListener.isPlaying
                && VoicePlayClickListener.currentPlayListener != null) {
            // 停止语音播放
            VoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }

        try {
            // 停止录音
            if (mVoiceRecorder.isRecording()) {
                mVoiceRecorder.discardRecording();
                recordingContainer.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }

        SocketThreadManager.getInstance().removeDataReceivedListener(TabMonitorFragment.this);
    }

    @Subscribe
    public void onEvent(OnTextSelectEvent event) {
        String msg = event.getContent();
        if (Tools.isNotEmpty(msg)) {
            mTxt2SendEtx.setText(mTxt2SendEtx.getText().toString().trim() + msg);
            mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
            mTxt2SendEtx.requestFocus();
            showSoftKeyboard();
            mTxt2SendEtx.setCursorVisible(true);
            foldLayout(false);
        }
    }

    @Subscribe
    public void onEvent(OnMediaResendEvent event) {
        SpeakForYouItem sfyi = event.getSfyi();
        switch (sfyi.SFYType) {
            case TEXT:
                speak(sfyi.Caption, sfyi);
                break;
            case VIDEO:
                playvideo(sfyi.episode_id, "cartoon", sfyi);
                break;
            case VOICE:
                break;
            default:
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private final Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            micImage.setImageDrawable(micImages[msg.what]);
        }
    };

    private final String toChatUsername = "dummyBaby2";

    private PowerManager.WakeLock wakeLock;

    private CountDownTimer mCDT;

    private final ChatType chatType = ChatType.ONE_TO_ONE;

    private void convert2Mp3(final String sourceFile, final SpeakForYouItem sfyi) {
        if (Tools.isEmpty(sourceFile)) {
            return;
        }

        File wavFile = new File(sourceFile);
        if (!wavFile.exists()) {
            return;
        }

        IConvertCallback callback = new IConvertCallback() {
            @Override
            public void onSuccess(File convertedFile) {
                uploadAudioFile(sourceFile.replace(".mp4", ".mp3"), sfyi);
            }

            @Override
            public void onFailure(Exception error) {
                CommonUtil.showToask(getActivity(), "ERROR: " + error.getMessage());
            }
        };

        // 语音上传中...

        AndroidAudioConverter.with(getActivity())
                .setFile(wavFile)
                .setFormat(AudioFormat.MP3)
                .setCallback(callback)
                .convert();
    }

    /**
     * upload audio file
     *
     * @param filePath
     * @param sfyi
     */
    private void uploadAudioFile(final String filePath, final SpeakForYouItem sfyi) {
        if (Tools.isEmpty(filePath)) {
            return;
        }

        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    // result.data : relative audio path
                    speakVoice(result.data/*msg*/, sfyi);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_MOBILE_I, lu.id);
                param_.put(HttpUtils.TAG_MODULE_I, "teacher/voice");
                return HttpUtils.startUploadRequest(HttpUtils.API_URL
                                + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
                        HttpUtils.TAG_POST_REQUEST);
            }
        }).execute("请检查网络连接!");
    }

    private void sendVoice(String fileName, final int length) {
        if (Tools.isEmpty(fileName) || !(new File(fileName).exists())) {
            return;
        }

        try {
            SpeakForYouItem sfyi = new SpeakForYouItem("",
                    SpeakForYouType.VOICE, 1, PosterType.Parent, DateUtils
                    .getNowDateString(), -1, -1);
            sfyi.audio_length = length;
            sfyi.Src = fileName;
            historyWordList.add(sfyi);

            if (sha == null) {
                sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
            }
            sha.updateData(historyWordList);
            sha.notifyDataSetChanged();

            scrollToBottom();
            convert2Mp3(fileName, sfyi);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startCountDown() {
        secondsLeftHint.setTextColor(getResources().getColor(
                R.color.setting_top_background));
        mCDT = new CountDownTimer(30000, 1000) {// CountDownTimer(edittext1.getText()+edittext2.getText())
            // also parse it to long

            @SuppressLint("ResourceAsColor")
            @Override
            public void onTick(long millisUntilFinished) {
                long secondsLeft = millisUntilFinished / 1000;
                if (secondsLeft == 4) {
                    secondsLeftHint.setTextColor(android.R.color.holo_red_dark);
                }
                secondsLeftHint.setText(secondsLeft + "");
            }

            @Override
            public void onFinish() {
                recordingContainer.setVisibility(View.INVISIBLE);
                try {
                    if (mVoiceRecorder != null) {
                        int length = mVoiceRecorder.stopRecoding();
                        if (length > 0) {
                            sendVoice(mVoiceRecorder.getVoiceFileName(), length);
                        } else if (length == -1) {
                            Toast.makeText(getApplicationContext(), "无录音权限",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "录音时间太短",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "发送失败，请检测服务器是否连接",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }.start();
    }

    public final float[] BT_SELECTED = new float[]{1, 0, 0, 0, -50, 0, 1, 0,
            0, -50, 0, 0, 1, 0, -50, 0, 0, 0, 1, 0};

    class PressToSpeakListen implements View.OnTouchListener {
        @SuppressLint({"ClickableViewAccessibility", "Wakelock"})
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (v != null && v.getBackground() != null) {
                        v.getBackground().setColorFilter(
                                new ColorMatrixColorFilter(BT_SELECTED));
                        v.setBackgroundDrawable(v.getBackground());
                    }

                    if (!CommonUtil.hasSDCard()) {
                        Toast.makeText(getActivity(), "发送语音需要sdcard支持！",
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    try {
                        v.setPressed(true);
                        wakeLock.acquire();
                        if (VoicePlayClickListener.isPlaying)
                            VoicePlayClickListener.currentPlayListener.stopPlayVoice();
                        recordingContainer.setVisibility(View.VISIBLE);
                        recordingContainer.bringToFront();
                        recordingHint.setText(getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                        mVoiceRecorder.startRecording(null, toChatUsername,
                                getApplicationContext());
                        startCountDown();
                    } catch (Exception e) {
                        e.printStackTrace();
                        v.setPressed(false);
                        if (wakeLock.isHeld())
                            wakeLock.release();
                        if (mVoiceRecorder != null)
                            mVoiceRecorder.discardRecording();
                        recordingContainer.setVisibility(View.INVISIBLE);
                        Toast.makeText(getApplicationContext(), R.string.recoding_fail,
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    return true;
                case MotionEvent.ACTION_MOVE: {
                    if (event.getY() < 0) {
                        recordingHint.setText(getString(R.string.release_to_cancel));
                        recordingHint
                                .setBackgroundResource(R.drawable.recording_text_hint_bg);
                    } else {
                        recordingHint.setText(getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    }
                    return true;
                }
                case MotionEvent.ACTION_CANCEL:
                    if (v != null && v.getBackground() != null) {
                        v.getBackground().clearColorFilter();
                        v.setBackgroundDrawable(v.getBackground());
                    }
                    return true;
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);

                    if (v != null && v.getBackground() != null) {
                        v.getBackground().clearColorFilter();
                        v.setBackgroundDrawable(v.getBackground());
                    }

                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (wakeLock.isHeld())
                        wakeLock.release();
                    if (event.getY() < 0) {
                        // discard the recorded audio.
                        if (mVoiceRecorder != null)
                            mVoiceRecorder.discardRecording();

                    } else {
                        // stop recording and send voice file
                        try {
                            if (mVoiceRecorder != null) {
                                int length = mVoiceRecorder.stopRecoding();
                                if (length > 0) {
                                    sendVoice(mVoiceRecorder.getVoiceFileName(), length);
                                } else if (length == -1) {
                                    Toast.makeText(getApplicationContext(), "无录音权限",
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getApplicationContext(), "录音时间太短",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "发送失败，请检测服务器是否连接",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                    stopCountDown();
                    return true;
                default:
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (mVoiceRecorder != null)
                        mVoiceRecorder.discardRecording();
                    return false;
            }
        }
    }

    private void stopCountDown() {
        if (mCDT != null) {
            mCDT.cancel();
        }
    }

    private void init() {
        micImages = new Drawable[]{
                getResources().getDrawable(R.drawable.record_1),
                getResources().getDrawable(R.drawable.record_2),
                getResources().getDrawable(R.drawable.record_3),
                getResources().getDrawable(R.drawable.record_4),
                getResources().getDrawable(R.drawable.record_5),
                getResources().getDrawable(R.drawable.record_6),};

        wakeLock = ((PowerManager) getActivity().getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");

        mVoiceRecorder = new VoiceRecorder(micImageHandler);
        btn_tospeak.setOnTouchListener(new PressToSpeakListen());

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorScheme(R.color.refresh_progress_1,
                R.color.refresh_progress_2, R.color.refresh_progress_3,
                R.color.refresh_progress_4);
        mLeUser = ((MyTeacherApp) getActivity().getApplication()).getUserTeacher();
        historyWordList = new ArrayList<SpeakForYouItem>();
        getHistoryRecords();
        this.mInflater = LayoutInflater.from(getActivity());
        loadTipWordCategory();
        mTagsViewPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                mViewPagerIndicators.check(rbIds.get(arg0));
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        // mViewPagerIndicators.check(rbIds.get(0));
        loadRecommendationData();

        mTxt2SendEtx.setHorizontallyScrolling(false);
        mTxt2SendEtx.setMinLines(2);
        mTxt2SendEtx.setMaxLines(4);
        mTxt2SendEtx
                .setOnEditorActionListener(new OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == 6) { // actionId 4 for actionDone And 6 for
                            // actionSend
                            // perform action what you want
                            return true;
                        } else
                            return false;
                    }
                });

        mTxt2SendEtx.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // hideSoftKeyboard();
                    mTxt2SendEtx.setHint(getResources().getString(
                            R.string.text_input_prompt));
                    mTxt2SendEtx.setCursorVisible(true);
                    foldLayout(false);

                    if (mTxt2SendEtx.getTag() == null || (boolean) mTxt2SendEtx.getTag()) {
                        showSoftKeyboard();
                        mTxt2SendEtx.setTag(true);
                    }
                    if (Tools.isEmpty(mTxt2SendEtx.getText().toString().trim())) {
                        mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
                        mTxt2SendEtx.setCursorVisible(true);
                    }
                } else {
                    hideSoftKeyboard();
                }
            }
        });

        mTxt2SendEtx.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String msg = mTxt2SendEtx.getText().toString().trim();
                    if (Tools.isNotEmpty(msg)) {
                        if (msg.length() > 100) {
                            DateUtils.showToast(getActivity(), "输入不能超过100个字符!");
                        } else {
                            mTxt2SendEtx.setText("");
                            SpeakForYouItem sfyi = new SpeakForYouItem(msg,
                                    SpeakForYouType.TEXT, 1, PosterType.Parent, DateUtils
                                    .getNowDateString(), -1, -1);
                            historyWordList.add(sfyi);

                            if (sha == null) {
                                sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                            }
                            sha.updateData(historyWordList);
                            sha.notifyDataSetChanged();

                            scrollToBottom();
                            speak(msg, sfyi);
                        }
                    } else {
                        mTxt2SendEtx.setText("");
                        DateUtils.showToast(getActivity(), "输入字符串为空!");

                    }
                    handled = true;
                }
                return handled;
            }
        });

        mTxt2SendEtx.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTxt2SendEtx != null) {
                    mTxt2SendEtx.requestFocus();
                }

                if (mTxt2SendEtx != null
                        && Tools.isNotEmpty(mTxt2SendEtx.getHint().toString())
                        && mTxt2SendEtx.getHint().toString().contains("给宝宝选个故事")) {
                    displayRecommend(ResourceType.Text);
                    mTxt2SendEtx.setCursorVisible(true);
                    foldLayout(false);
                }

                if (mTxt2SendEtx != null
                        && Tools.isNotEmpty(mTxt2SendEtx.getHint().toString())
                        && mTxt2SendEtx.getHint().toString().contains("输入文字让小小班")) {
                    if (Tools.isEmpty(mTxt2SendEtx.getText().toString().trim())) {
                        mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
                        mTxt2SendEtx.setCursorVisible(true);
                    }
                }
                showSoftKeyboard();
            }
        });

        loadLocalBgResource();
    }

    private void loadLocalBgResource() {
        ArrayList<AlbumCollectionItem> list = new ArrayList<AlbumCollectionItem>();

        AlbumCollectionItem aci1 = new AlbumCollectionItem();
        aci1.setName("默认背景");
        aci1.setId(1);
        list.add(aci1);

        aci1 = new AlbumCollectionItem();
        aci1.setName("圣诞礼物");
        aci1.setId(2);
        list.add(aci1);

        aci1 = new AlbumCollectionItem();
        aci1.setName("保护自己");
        aci1.setId(3);
        list.add(aci1);

        aci1 = new AlbumCollectionItem();
        aci1.setName("小小拜年");
        aci1.setId(4);
        list.add(aci1);

        aci1 = new AlbumCollectionItem();
        aci1.setName("穿越星空");
        aci1.setId(5);
        list.add(aci1);

        aci1 = new AlbumCollectionItem();
        aci1.setName("相亲相爱");
        aci1.setId(6);
        list.add(aci1);

        aci1 = new AlbumCollectionItem();
        aci1.setName("现拍背景");
        aci1.setId(7);
        list.add(aci1);

        aci1 = new AlbumCollectionItem();
        aci1.setName("相册选择");
        aci1.setId(8);
        list.add(aci1);

        ChatWallPaperAapter cwpa = new ChatWallPaperAapter(getActivity(), list);
        cwpa.setPhotoSourceDelegate(new PhotoSourceDelegate() {
            @Override
            public void onPhotoSource(int source) {
                switch (source) {
                    case 1:
                        Uri tmpUri1 = getUriToResource(getActivity(),
                                android.R.color.transparent);
                        setChatBgWallpaper(Color.parseColor("#f1f1f1"), tmpUri1);
                        break;
                    case 2:
                        Uri tmpUri2 = getUriToResource(getActivity(),
                                R.drawable.christmas_theme);
                        setChatBgWallpaper(android.R.color.transparent, tmpUri2);
                        break;
                    case 3:
                        Uri tmpUri3 = getUriToResource(getActivity(),
                                R.drawable.foggy_theme);
                        setChatBgWallpaper(android.R.color.transparent, tmpUri3);
                        break;
                    case 4:
                        Uri tmpUri4 = getUriToResource(getActivity(),
                                R.drawable.newspring_theme);
                        setChatBgWallpaper(android.R.color.transparent, tmpUri4);
                        break;
                    case 5:
                        Uri tmpUri5 = getUriToResource(getActivity(),
                                R.drawable.through_universe_theme);
                        setChatBgWallpaper(android.R.color.transparent, tmpUri5);
                        break;
                    case 6:
                        Uri tmpUri6 = getUriToResource(getActivity(),
                                R.drawable.love_theme);
                        setChatBgWallpaper(android.R.color.transparent, tmpUri6);
                        break;

                    case 7:
                        String status = Environment.getExternalStorageState();
                        if (status.equals(Environment.MEDIA_MOUNTED)) {
                            if (!PHOTO_DIR.exists()) {
                                PHOTO_DIR.mkdirs();// 创建照片的存储目录
                            }
                            fileName = System.currentTimeMillis() + ".jpg";
                            mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
                            Intent intentC = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                            if (Build.VERSION.SDK_INT >= 24) {
                                Uri imageUri = FileProvider.getUriForFile(
                                        getActivity(), "com.haoduoaiteacher.fileprovider",
                                        mCurrentPhotoFile);
                                intentC.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                intentC.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                            } else {
                                intentC.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(mCurrentPhotoFile));
                            }
                            startActivityForResult(intentC, CAMERA_WITH_DATA);
                        } else {
                            // toastShow("没有SD卡");
                            CommonUtil.showToask(getActivity(), "没有SD卡");
                        }
                        break;
                    case 8:
                        Intent intent = new Intent();
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.setType("image/*");
                        if (Build.VERSION.SDK_INT < 19) {
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                        } else {
                            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                        }
                        startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
                        // doHandlePhoto(PIC_FROM＿LOCALPHOTO);
                        break;
                    default:
                        DateUtils.showToast(getActivity(), "全新壁纸，尽情期待!");
                        break;
                }
            }
        });

        mBgSelectGv.setAdapter(cwpa);
    }

    private void setChatBgWallpaper(int listViewColor, Uri backgroundUri) {
        mHistoryLV.setBackgroundColor(listViewColor);
        mChangeBgImg.setImageURI(backgroundUri);
        if (backgroundUri != null)
            mChatBgPath = backgroundUri.toString();
        mListViewColor = listViewColor;
    }

    public static final Uri getUriToResource(@NonNull Context context,
                                             @AnyRes int resId) throws Resources.NotFoundException {
        /** Return a Resources instance for your application's package. */
        Resources res = context.getResources();
        /**
         * Creates a Uri which parses the given encoded URI string.
         *
         * @param uriString
         *          an RFC 2396-compliant, encoded URI
         * @throws NullPointerException
         *           if uriString is null
         * @return Uri for this given uri string
         */
        Uri resUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + res.getResourcePackageName(resId) + '/'
                + res.getResourceTypeName(resId) + '/'
                + res.getResourceEntryName(resId));
        /** return uri */
        return resUri;
    }

    /**
     * 调用图片剪辑程序
     */
    @SuppressLint("InlinedApi")
    public Intent getCropImageIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setType("image/*");

        if (Build.VERSION.SDK_INT < 19) {
            setIntentParams(intent);
        } else {
            // TODO
        }
        return intent;
    }

    /**
     * 设置公用参数
     */
    private void setIntentParams(Intent intent) {
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("noFaceDetection", true); // no face detection
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mResultURI);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
    }

    private void setIntentResult(Uri tmpFile) {
        LeXiaoXiaoBanLog.e(TAG, "set result");
        Intent resultIntent = new Intent();
        resultIntent.putExtra("image", tmpFile.toString());
        getActivity().setResult(RESULT_OK, resultIntent);

        LePreference.getInstance().save("speak_for_you_listview_bg_color",
                android.R.color.transparent);

        LePreference.getInstance().save("speak_for_you_wallpaper",
                tmpFile.toString());

        setChatBgWallpaper(android.R.color.transparent, tmpFile);
        // finish();
    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        String fileName = System.currentTimeMillis() + ".jpg";
        if (!PHOTO_DIR.exists()) {
            PHOTO_DIR.mkdirs();// 创建照片的存储目录
        }
        mCacheFile = new File(PHOTO_DIR, fileName);
        Uri outputUri = Uri.fromFile(new File(mCacheFile.getPath()));
        String url = FileUtils.getPath(getActivity(), uri);

        Intent intent = new Intent("com.android.camera.action.CROP");
        // sdk>=24
        if (Build.VERSION.SDK_INT >= 24) {

            Uri imageUri = FileProvider.getUriForFile(getActivity(), "com.haoduoaiteacher.fileprovider",
                    new File(url));// 通过FileProvider创建一个content类型的Uri
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra("noFaceDetection", true);// 去除默认的人脸识别，否则和剪裁匡重叠
            intent.setDataAndType(imageUri, "image/*");

            // 19=<sdk<24
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && Build.VERSION.SDK_INT < 24) {
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");

            // sdk<19
        } else {
            intent.setDataAndType(uri, "image/*");
        }
        intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
        intent.putExtra("aspectX", 19);// 这两项为裁剪框的比例.
        intent.putExtra("aspectY", 20);// x:y=1:2
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 500);
        intent.putExtra("output", outputUri);
        intent.putExtra("outputFormat", "JPEG");// 返回格式
        startActivityForResult(intent, CROP_PHOTO);
    }

    private void inflateHistoryData(List<SpeakFouYouRecordItem> sfyris) {
        if (historyWordList != null) {
            int size = sfyris.size();
            int i = 0;
            for (; i != size; i++) {
                SpeakFouYouRecordItem item = sfyris.get(i);
                if (Tools.isNotEmpty(item.audio)) {
                    PosterType psType = PosterType.Child;
                    if (Tools.isNotEmpty(item.poster) && item.poster.equalsIgnoreCase("app")) {
                        psType = PosterType.Parent;
                    }
                    SpeakForYouItem sfyi = new SpeakForYouItem(item.audio, SpeakForYouType.VOICE, item.success, psType, item.created_at, item.id, item.episode_id);
                    sfyi.hasRead = item.audio_read;
                    sfyi.length = Integer.valueOf(item.audio_length).intValue();
                    sfyi.id = item.id;
                    historyWordList.add(0, sfyi);
                } else if (Tools.isNotEmpty(item.poster) && item.poster.equals("turing")) {
                    historyWordList.add(0, new SpeakForYouItem(item.content, SpeakForYouType.TEXT, item.success, PosterType.Turing, item.created_at, item.id, item.episode_id));
                } else if (Tools.isNotEmpty(item.content)) {
                    if (Tools.isNotEmpty(item.img) && item.img.contains(".jpg") || Tools.isNotEmpty(item.img) && item.img.contains(".png")) {
                        historyWordList.add(0, new SpeakForYouItem(item.content, item.img,
                                item.id, item.episode_id, SpeakForYouType.VIDEO, item.success,
                                PosterType.Parent, item.created_at));
                    } else {
                        historyWordList.add(0, new SpeakForYouItem(item.content, SpeakForYouType.TEXT, item.success, PosterType.Parent, item.created_at, item.id, item.episode_id));
                    }
                }


            }
            if(getActivity()!=null){

            sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
            mHistoryLV.setAdapter(sha);
            mHistoryLV.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    foldLayout(false);
                }
            });

            sha.notifyDataSetChanged();
            }
        }
    }

    private void speakVoice(final String relativeAudioPath, final SpeakForYouItem sfyi) {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                boolean isSucc = true;
                if (result.isSuccess()) {
                    sfyi.State = SendState.SUCCESS;
                } else {
                    sfyi.State = SendState.FAILED;
                    isSucc = false;
                    if (Tools.isNotNullStr(result.data)) {
                        DateUtils.showToast(getActivity(), result.data);
                    }
                }

                if ((mSelectPostion - 1) < mStudentDeviceModelList.size() && (mSelectPostion - 1) >= 0) {
                    String macIddd = mStudentDeviceModelList.get(mSelectPostion - 1).machine_id;
                    String strStatus = mDeviceStatusMap.get(macIddd);
                    if (Tools.isNotEmpty(strStatus)) {
                        if (strStatus.equals("-1") || strStatus.equals("-2")) {
                            sfyi.State = SendState.FAILED;
                            isSucc = false;
                        }
                    }
                }
                sfyi.relativeAudioPath = relativeAudioPath;
                uploadRecord(sfyi.id, sfyi.Src, sfyi.Caption, isSucc, 0,
                        sfyi);
                if (sha == null) {
                    sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                } else {
                    sha.notifyDataSetChanged();
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                sfyi.State = SendState.SENDING;
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put("audio", relativeAudioPath);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                if (mSelectPostion == 0) {
                    param_.put("stype", 1);
                } else {
                    param_.put("stype", 2);
                    if (Tools.isNotEmpty(machine_ids) && (mSelectPostion - 1) >= 0) {
                        param_.put("machine_ids", mStudentDeviceModelList.get(mSelectPostion - 1).machine_id);
                    }
                }

                return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/teacher/speech_device",
                        param_, HttpUtils.TAG_POST_REQUEST);
            }
        }).execute();
    }

    private void speak(final String content, final SpeakForYouItem sfyi) {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                boolean isSucc = true;
                if (result.isSuccess()) {
                    sfyi.State = SendState.SUCCESS;
                } else {
                    sfyi.State = SendState.FAILED;
                    isSucc = false;
                    if (Tools.isNotNullStr(result.data)) {
                        DateUtils.showToast(getActivity(), result.data);
                    }
                }

                if ((mSelectPostion - 1) < mStudentDeviceModelList.size() && (mSelectPostion - 1) >= 0) {
                    String macIddd = mStudentDeviceModelList.get(mSelectPostion - 1).machine_id;
                    String strStatus = mDeviceStatusMap.get(macIddd);

                    if (Tools.isNotEmpty(strStatus)) {
                        if (strStatus.equals("-1") || strStatus.equals("-2")) {
                            sfyi.State = SendState.FAILED;
                            isSucc = false;
                        }
                    }
                }

                uploadRecord(sfyi.id, sfyi.Src, sfyi.Caption, isSucc, 0,
                        sfyi);

                if (sha == null) {
                    sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                } else {
                    sha.notifyDataSetChanged();
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                sfyi.State = SendState.SENDING;
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put("content", content);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                if (mSelectPostion == 0) {
                    param_.put("stype", 1);
                } else {
                    param_.put("stype", 2);
                    if (Tools.isNotEmpty(machine_ids) && (mSelectPostion - 1) >= 0) {
                        param_.put("machine_ids", mStudentDeviceModelList.get(mSelectPostion - 1).machine_id);
                    }
                }

                return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/teacher/speech_device",
                        param_, HttpUtils.TAG_POST_REQUEST);
            }
        }).execute();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            Log.i("test","run");

            classname = SPUtil.getString(getActivity(), "classnamexxj", "");
            userclass = SPUtil.getString(getActivity(), "classnumxxj", "1");
            account = SPUtil.getString(getActivity(), "account", "");


            Log.i("test","userclass"+userclass);
            getBindDevices();
//            if (mStoryAdapter != null) {
//                mStoryAdapter.mDeviceStatusMap = mDeviceStatusMap;
//                mStoryAdapter.notifyDataSetChanged();
//            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("code", 202);
            jsonObject.put("act", "speech");
            jsonObject.put("op", "stop");
            SocketThreadManager.getInstance().send(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void scrollMyListViewToBottom() {
        mHistoryLV.post(new Runnable() {
            @Override
            public void run() {
                // Select the last row so it will scroll into view...
                if (sha == null) {
                    sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                }

                if (sha != null)
                    mHistoryLV.setSelection(sha.getCount() - 1);
            }
        });
    }

    private void getHistoryRecords() {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @SuppressWarnings("unchecked")
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    JSONObject jo;
                    try {
                        jo = new JSONObject(result.data);
                        List<SpeakFouYouRecordItem> sfyris = (List<SpeakFouYouRecordItem>) JsonSerializer
                                .getInstance().deserialize(jo.getString("data"),
                                        ArrayList.class, SpeakFouYouRecordItem.class);
                        if (Tools.isNotEmpty(sfyris) && sfyris.size() != 0) {
                            mLastPage++;
                            inflateHistoryData(sfyris);
                            if (mLastPage == 2)
                                scrollMyListViewToBottom();
                        } else {
                            sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                            mHistoryLV.setAdapter(sha);
                            mHistoryLV.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    foldLayout(false);
                                }
                            });
                            sha.notifyDataSetChanged();
                        }
                        mSwipeRefreshLayout.setRefreshing(false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put("page", mLastPage);

                if (mSelectPostion == 0) {
                    param_.put("stype", 1);
                } else {
                    param_.put("stype", 2);
                    if (Tools.isNotEmpty(mStudentDeviceModelList) && !mStudentDeviceModelList.isEmpty()
                            && (mSelectPostion - 1) >= 0) {
                        param_.put("mac_id", mStudentDeviceModelList.get(mSelectPostion - 1).machine_id);
                    }
                }

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/teacher/history/sound", param_,
                        HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    private boolean needRefresh;

    private void uploadRecord(final int id, final String imgUrl,
                              final String content, final boolean success, final int episode_id,
                              final SpeakForYouItem sfyi) {
        needRefresh = false;
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (id == -1 && result.isSuccess()) {
                    JSONObject jo;
                    try {
                        jo = new JSONObject(result.data);
                        if (jo.has("created_id")) {
                            int _id = jo.getInt("created_id");
                            sfyi.id = _id;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                if (needRefresh) {
                    loadTipWordsByCategory(0, tipWordList.get(0).id, true);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                if (Tools.isNotEmpty(imgUrl)) {
                    param_.put("img", imgUrl);
                }

                if (sfyi.SFYType == SpeakForYouType.VOICE) {
                    if (Tools.isNotEmpty(sfyi.relativeAudioPath)) {
                        param_.put("audio", sfyi.relativeAudioPath);
                    }
                    if (Tools.isNotEmpty(sfyi.audio_length)) {
                        param_.put("audio_length", sfyi.audio_length);
                    }
                    if (sfyi.posterType == PosterType.Parent) {
                        param_.put("audio_read", 1);
                    }
                } else {
                    param_.put("content", content);
                }

                if (episode_id != 0) {
                    param_.put("episode_id", episode_id);
                }

                if (success) {
                    param_.put("success", 1);
                } else {
                    param_.put("success", 0);
                }

                if (mSelectPostion == 0) {
                    param_.put("stype", 1);
                } else {
                    param_.put("stype", 2);
                    if (Tools.isNotEmpty(machine_ids) && (mSelectPostion - 1) >= 0) {
                        param_.put("mac_id", mStudentDeviceModelList.get(mSelectPostion - 1).machine_id);
                    }
                }

                int prompt_text_id = -1;
                if (sfyi.SFYType == SpeakForYouType.TEXT
                        && sfyi.posterType == PosterType.Parent) {
                    if (tipWordListSpArray != null
                            && !tipWordListSpArray.get(0).isEmpty()) {
                        for (TipWordCategoryItem item : tipWordListSpArray.get(0)) {
                            if (content.equalsIgnoreCase(item.name)) {
                                prompt_text_id = item.id;
                                break;
                            }
                        }
                    }
                }

                if (prompt_text_id != -1) {
                    param_.put("prompt_text_id", prompt_text_id);
                    needRefresh = true;
                }

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/teacher/history/sound"/* + (id == -1 ? "NA" : id)*/,
                        param_, HttpUtils.TAG_POST_REQUEST);
            }
        }).execute();
    }

    private void hideSoftKeyboard() {
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void showSoftKeyboard() {
        final View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, 0);
        }
    }

    private void expandLayout() {
        RelativeLayout.LayoutParams iParams = (RelativeLayout.LayoutParams) mInputSelectionLayout
                .getLayoutParams();
        iParams.height = Tools.getPixelByDip(getActivity(), 264);
        iParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mInputSelectionLayout.setLayoutParams(iParams);
        RelativeLayout.LayoutParams cParams = (RelativeLayout.LayoutParams) mCenterLayout
                .getLayoutParams();
        cParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mCenterLayout.setLayoutParams(cParams);
    }

    private void foldLayout(boolean imgSelect) {
        RelativeLayout.LayoutParams iParams = (RelativeLayout.LayoutParams) mInputSelectionLayout
                .getLayoutParams();
        iParams.height = 0;
        iParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mInputSelectionLayout.setLayoutParams(iParams);
        RelativeLayout.LayoutParams cParams = (RelativeLayout.LayoutParams) mCenterLayout
                .getLayoutParams();
        cParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mCenterLayout.setLayoutParams(cParams);
        mRadioImg.setImageResource(R.drawable.radio_icon);
        mImeImg.setImageResource(R.drawable.ime_icon);
        if (imgSelect) {
            mImg_voice.setImageResource(R.drawable.chatfrom_voice_playing_f3_blue);
        } else {
            mImg_voice.setImageResource(R.drawable.chatfrom_voice_playing_f3);
        }

        mChatBgImg.setImageResource(R.drawable.chat_bg_icon);
    }

    private void loadRecommendationData() {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @SuppressWarnings("unchecked")
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    List<AlbumItem> recommendAlbums = (List<AlbumItem>) JsonSerializer
                            .getInstance().deserialize(result.data, ArrayList.class,
                                    AlbumItem.class);
                    if (Tools.isNotEmpty(recommendAlbums)) {
                        if(getActivity()!=null){
                            setRecommendView(recommendAlbums);
                        }

                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/catalog/radio/recommand", param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();
    }

    private void loadTipWordCategory() {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @SuppressWarnings("unchecked")
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    tipWordList = (List<TipWordCategoryItem>) JsonSerializer.getInstance().deserialize(result.data, ArrayList.class, TipWordCategoryItem.class);
                    if (Tools.isNotEmpty(tipWordList) && !tipWordList.isEmpty()) {
                        for (int i = 0; i < tipWordList.size(); i++) {
                            loadTipWordsByCategory(i, tipWordList.get(i).id, false);
                        }
                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/operation/sounding_for_you/type", param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();
    }

    private void loadTipWordsByCategory(final int pos, final int type_id, final boolean update) {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @SuppressWarnings("unchecked")
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                ++tipIndex;
                if (result.isSuccess()) {
                    List<TipWordCategoryItem> wlist = (List<TipWordCategoryItem>) JsonSerializer
                            .getInstance().deserialize(result.data, ArrayList.class,
                                    TipWordCategoryItem.class);

                    tipWordListSpArray.put(pos, wlist);
                }

                if (tipIndex >= tipWordList.size() || update) {
                    tipIndex = 0;
                    initTextCategoryLayout();

                    if (update) {
                        needRefresh = false;
                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/operation/sounding_for_you/type_" + type_id + "/text",
                        param_, HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    private void buildCircles() {
        recommend_rbIds = new ArrayList<Integer>();
        int i = 0;
        for (; i < 2; i++) {
            LayoutParams rbParams = new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            rbParams.setMargins(Tools.getPixelByDip(getActivity(), 10), 0,
                    Tools.getPixelByDip(getActivity(), 10), 0);
            RadioButton rb = new RadioButton(getActivity());
            rb.setButtonDrawable(R.drawable.gridview_pager_indicator);
            rb.setId(i * 1);
            rb.setPadding(Tools.getPixelByDip(getApplicationContext(), 5), 0,
                    Tools.getPixelByDip(getApplicationContext(), 5), 0);
            rb.setLayoutParams(rbParams);
            recommend_rbIds.add(rb.getId());
            mCircleRg.addView(rb);
        }

    }

    private class RecommendPagerAdapter extends FragmentStatePagerAdapter {

        private List<AlbumItem> mAlbumItemList;
        private OnRecommendItemClickListener mOnRecommendItemClickListener;

        public RecommendPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public RecommendPagerAdapter(FragmentManager fm, List<AlbumItem> ais,
                                     OnRecommendItemClickListener listener) {
            this(fm);
            mAlbumItemList = ais;
            mOnRecommendItemClickListener = listener;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public Fragment getItem(int pos) {
            pos %= 2;
            int startIndex = pos * 8;
            int endIndex = Math.min((1 + pos) * 8, mAlbumItemList.size());
            return new GridViewFragment(mAlbumItemList.subList(startIndex, endIndex),
                    mOnRecommendItemClickListener);
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

    private void setRecommendView(List<AlbumItem> aiList) {

        mRecommendPagerAdapter = new RecommendPagerAdapter(
                getActivity().getSupportFragmentManager(), aiList,
                new OnRecommendItemClickListener() {
                    @Override
                    public void onRecommendItemClick(AlbumItem ai) {
                        SpeakForYouItem sfyi = new SpeakForYouItem(ai.title,
                                ai.album_cover, ai.id, ai.album_id, SpeakForYouType.VIDEO,
                                1, PosterType.Parent, DateUtils.getNowDateString());
                        historyWordList.add(sfyi);

                        if (sha == null) {
                            sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                        }

                        sha.updateData(historyWordList);
                        if (sha != null)
                            sha.notifyDataSetChanged();
                        scrollToBottom();
                        playvideo(ai.id, "cartoon", sfyi);
                    }
                });

        mRecommendVp.setAdapter(mRecommendPagerAdapter);

        mRecommendVp.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                if (arg0 < recommend_rbIds.size()) {
                    mCircleRg.check(recommend_rbIds.get(arg0));
                }
                // loadRecommendationData(arg0);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void playvideo(final int sid, final String status, final SpeakForYouItem sfyi) {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                boolean isSucc = true;
                if (result.isSuccess()) {
                    DateUtils.showToast(getActivity(), "已推送到设备播放");
                    sfyi.State = SendState.SUCCESS;

                    if (sha == null) {
                        sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                    }
//                    if (sha != null)
//                        sha.notifyDataSetChanged();
//                    uploadRecord(sfyi.id, sfyi.Src, sfyi.Caption, result.isSuccess(),
//                            sid, sfyi);
                } else {
                    DateUtils.showToast(getActivity(), "设备不在线");
                    sfyi.State = SendState.FAILED;
                    LeConfig.isDeviceConnect = false;
                    isSucc = false;
                }

                if ((mSelectPostion - 1) < mStudentDeviceModelList.size() && (mSelectPostion - 1) >= 0) {
                    String macIddd = mStudentDeviceModelList.get(mSelectPostion - 1).machine_id;
                    String strStatus = mDeviceStatusMap.get(macIddd);

                    if (Tools.isNotEmpty(strStatus)) {
                        if (strStatus.equals("-1") || strStatus.equals("-2")) {
                            sfyi.State = SendState.FAILED;
                            isSucc = false;
                        }
                    }
                }

                if (sha == null) {
                    sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                }

                if (sha != null)
                    sha.notifyDataSetChanged();
                uploadRecord(sfyi.id, sfyi.Src, sfyi.Caption, result.isSuccess(),
                        sid, sfyi);

            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                sfyi.State = SendState.SENDING;
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                int uid = -1, volume = -1, minutes = -1;
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                if (mSelectPostion == 0) {
                    param_.put("stype", 1);
                } else {
                    param_.put("stype", 2);
                    if (Tools.isNotEmpty(machine_ids) && (mSelectPostion - 1) >= 0) {
                        param_.put("machine_ids", mStudentDeviceModelList.get(mSelectPostion - 1).machine_id);
                    }
                }
//                if (sid != -1) {
//                    param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
//                }

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/teacher/cartoon_device" + "/" + sid, param_,
                        HttpUtils.TAG_POST_REQUEST);

            }
        }).execute();
    }

    private void scrollToBottom() {
        mHistoryLV.post(new Runnable() {
            @Override
            public void run() {
                if (sha == null) {
                    sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                }
                if (sha != null)
                    mHistoryLV.setSelection(sha.getCount() - 1);
            }
        });
    }

    private int mCurTypeIndex = 0;

    private void highlightSelection(int pos) {
        if (selectedTextViewId != -1) {
            for (TextView tv : categoryTextViewList) {
                if (tv.getId() == selectedTextViewId) {
                    tv.setTextColor(Color.argb(255, 43, 172, 252));
                } else {
                    tv.setTextColor(oldColors);
                }
            }
            // int subIndex = selectedTextViewId / 11;
            mCurTypeIndex = pos;
            if(getActivity()!=null){
                PagerAdapter pa = new TagsPagerAdapter(getActivity().getSupportFragmentManager(),
                        tipWordListSpArray.get(pos));
                mTagsViewPager.setAdapter(pa);
                pa.notifyDataSetChanged();
            }

        }
    }

    private void initTextCategoryLayout() {
        int i = 0;
        int size = tipWordList.size();
        rbIds = new ArrayList<Integer>();
        categoryTextViewList = new ArrayList<TextView>();

        mHLayout.removeAllViews();

        for (; i < size; i++) {
            String cur = tipWordList.get(i).name;
            View hChild = mInflater.inflate(R.layout.text_category_item, null);
            final TextView categoryBtn = (TextView) hChild
                    .findViewById(R.id.category_tv);
            categoryBtn.setText(cur);
            categoryBtn.setPadding(Tools.getPixelByDip(getApplicationContext(), 20), 0,
                    Tools.getPixelByDip(getApplicationContext(), 20), 0);
            categoryBtn.setId(11 * i);
            categoryTextViewList.add(categoryBtn);
            if (i == 0) {
                oldColors = categoryBtn.getTextColors(); // save original colors
                selectedTextViewId = categoryBtn.getId();
            }
            categoryBtn.setTag(i);
            categoryBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectedTextViewId = categoryBtn.getId();
                    highlightSelection((int) categoryBtn.getTag());
                }
            });
            LayoutParams tvParams = new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            hChild.setLayoutParams(tvParams);
            mHLayout.addView(hChild);
        }

        highlightSelection(0);
    }

    private class TagsPagerAdapter extends FragmentStatePagerAdapter {
        private List<TipWordCategoryItem> tags;

        public TagsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public TagsPagerAdapter(FragmentManager fm, List<TipWordCategoryItem> strArray) {
            this(fm);
            tags = strArray;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public Fragment getItem(int pos) {
            return TagsFragment.newInstance(tags);
        }

        @Override
        public int getCount() {
            // return tags.length;
            return 1;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.radio_img:
                displayRecommend(ResourceType.Video);
                break;
            case R.id.ime_img:
                displayRecommend(ResourceType.Text);
                break;
            case R.id.img_voice:
                displayRecommend(ResourceType.Voice);
                break;
            case R.id.chat_bg_img:
                displayRecommend(ResourceType.Background);
                break;
            case R.id.ask_search_tv:
                Intent intent = new Intent(getActivity(), WebViewContainerActivity.class);
                intent.putExtra("h5url",
                        "http://www.xiaoxiaoban.com.cn/search/search.html");
                // intent.putExtra("speak", "ask");
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                break;
            default:
                break;
        }
    }

    private void displayRecommend(ResourceType rt) {
        hideSoftKeyboard();
        mTxt2SendEtx.setText("");
        mTxt2SendEtx.setCursorVisible(false);

        switch (rt) {
            case Voice:
                mTagsViewPager.setVisibility(View.GONE);
                bottomHS.setVisibility(View.GONE);
                mBgSelectGv.setVisibility(View.GONE);
                mRecommendVp.setVisibility(View.GONE);
                mCircleRg.setVisibility(View.GONE);
                mViewPagerIndicators.setVisibility(View.GONE);
                mTxt2SendEtx.setHint(getResources().getString(
                        R.string.quick_story_input_prompt));
                mRadioImg.setImageResource(R.drawable.radio_icon_highlight);
                mImeImg.setImageResource(R.drawable.ime_icon);
                mImg_voice.setImageResource(R.drawable.chatfrom_voice_playing_f3_blue);
                mChatBgImg.setImageResource(R.drawable.chat_bg_icon);

                btn_tospeak.setVisibility(View.VISIBLE);
                mTxt2SendEtx.setVisibility(View.GONE);

                mTxt2SendEtx.setCursorVisible(true);
                foldLayout(true);
                break;
            case Video:
                mTagsViewPager.setVisibility(View.GONE);
                bottomHS.setVisibility(View.GONE);
                mBgSelectGv.setVisibility(View.GONE);
                mRecommendVp.setVisibility(View.VISIBLE);
                mCircleRg.setVisibility(View.VISIBLE);
                mViewPagerIndicators.setVisibility(View.GONE);
                mTxt2SendEtx.setHint(getResources().getString(
                        R.string.quick_story_input_prompt));
                mRadioImg.setImageResource(R.drawable.radio_icon_highlight);
                mImeImg.setImageResource(R.drawable.ime_icon);
                mImg_voice.setImageResource(R.drawable.chatfrom_voice_playing_f3);
                mChatBgImg.setImageResource(R.drawable.chat_bg_icon);
                mTxt2SendEtx.setVisibility(View.VISIBLE);
                btn_tospeak.setVisibility(View.GONE);
                expandLayout();
                break;
            case Text:
                mTagsViewPager.setVisibility(View.VISIBLE);
                bottomHS.setVisibility(View.VISIBLE);
                mRecommendVp.setVisibility(View.GONE);
                mCircleRg.setVisibility(View.GONE);
                mBgSelectGv.setVisibility(View.GONE);
                mViewPagerIndicators.setVisibility(View.VISIBLE);
                mTxt2SendEtx.setHint(getResources().getString(
                        R.string.quick_text_input_prompt));
                mRadioImg.setImageResource(R.drawable.radio_icon);
                mImeImg.setImageResource(R.drawable.ime_icon_highlight);
                mImg_voice.setImageResource(R.drawable.chatfrom_voice_playing_f3);
                mChatBgImg.setImageResource(R.drawable.chat_bg_icon);
                mTxt2SendEtx.setVisibility(View.VISIBLE);
                btn_tospeak.setVisibility(View.GONE);
                mTxt2SendEtx.setTag(false);
                if (Tools.isEmpty(mTxt2SendEtx.getText().toString().trim())) {
                    mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
                    mTxt2SendEtx.requestFocus();
                    mTxt2SendEtx.setCursorVisible(true);
                }

                expandLayout();
                break;
            case Background:
                mBgSelectGv.setVisibility(View.VISIBLE);
                mTagsViewPager.setVisibility(View.GONE);
                bottomHS.setVisibility(View.GONE);
                mRecommendVp.setVisibility(View.GONE);
                mCircleRg.setVisibility(View.GONE);
                mRadioImg.setImageResource(R.drawable.radio_icon);
                mImeImg.setImageResource(R.drawable.ime_icon);
                mImg_voice.setImageResource(R.drawable.chatfrom_voice_playing_f3);
                mChatBgImg.setImageResource(R.drawable.chat_bg_icon_highlight);
                mTxt2SendEtx.setVisibility(View.VISIBLE);
                btn_tospeak.setVisibility(View.GONE);
                expandLayout();
                break;
            default:
                mTxt2SendEtx.setVisibility(View.VISIBLE);
                btn_tospeak.setVisibility(View.GONE);
                expandLayout();
                break;
        }

    }

    @Override
    public void onDataReceived(String data) {
        if (Tools.isNotEmpty(data)) {
            try {
                JSONObject jsonData = new JSONObject(data.toString());
                if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("act")) {
                    SpeakForYouItem sfyi = null;
                    String actStr = jsonData.getString("act");
                    if (actStr.contains("audio")) {
                        String realData = jsonData.getString("data");
                        if (Tools.isNotEmpty(realData)) {
                            JSONObject jo = new JSONObject(realData);
                            int id = jo.getInt("id");
                            String src = jo.getString("src");
                            int length = jo.getInt("length");
                            sfyi = new SpeakForYouItem(src, SpeakForYouType.VOICE, 1,
                                    PosterType.Child, DateUtils.getNowDateString(), id, -1);
                            sfyi.id = id;
                            sfyi.length = length;
                            sfyi.hasRead = 0;
                        }
                    } else if (actStr.contains("speech_teacher")) {
                        String realData = jsonData.getString("data");
                        if (Tools.isNotEmpty(realData)) {
                            JSONObject jo = new JSONObject(realData);
                            int id = jo.getInt("id");
                            String src = jo.getString("src");
                            int length = jo.getInt("length");
                            String stype = jo.getString("stype");
                            String from = jo.getString("from");
                            String to = jo.getString("to");

                            if (Tools.isNotEmpty(stype)) {
                                if (stype.equals("1") && mSelectPostion == 0) {
                                } else if (stype.equals("2") && Tools.isNotEmpty(from)) {
                                    // 1 to 1 single
                                    if ((mSelectPostion - 1) >= 0 && mStudentDeviceModelList.get(mSelectPostion - 1).machine_id.contains(from)) {
                                        sfyi = new SpeakForYouItem(src, SpeakForYouType.VOICE, 1,
                                                PosterType.Child, DateUtils.getNowDateString(), id, -1);
                                        sfyi.id = id;
                                        sfyi.length = length;
                                        sfyi.hasRead = 0;
                                    }
                                }
                            }
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loadUnreadMsg();
                            }
                        });
                    } else if (actStr.contains("turing")) {
                    } else if (actStr.contains("Device_Login")) {
                        LeConfig.isDeviceConnect = true;
                    } else if (actStr.contains("Device_Logout")) {
                        LeConfig.isDeviceConnect = false;
                    } else if (actStr.contains("Device_APP_Connection_Switched")) {
                        // TODO
                    }
                    if (sfyi != null) {
                        historyWordList.add(sfyi);
                        if (sha == null) {
                            sha = new SpeakWordHistoryAdapter(getActivity(), historyWordList, TabMonitorFragment.this);
                        } else {
                            sha.updateData(historyWordList);
                        }

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sha.notifyDataSetChanged();
                                scrollToBottom();
                            }
                        });
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onRefresh() {
        mSwipeRefreshLayout.setRefreshing(true);
        getHistoryRecords();
    }

    @Override
    public void onRemoteLogin() {
    }

    @Override
    public void onConnectionChanged(final boolean connect) {
    }

    @Override
    public void onPowerChanged(int power) {
    }

    @Override
    public void onUpgrade(int updatingStatus) {
    }

    @Override
    public void onCheckDeviceVersion(String version) {
    }

    @Override
    public void onPlayNextFailed() {

    }

    @Override
    public void onPlayPrevFailed() {
    }

    @Override
    public void onPlayMedia(final PlayState playState, MediaType type,
                            JSONObject data) {
    }

    @Override
    public void onReceivedVoiceMessage(String streamUrl) {
    }

    @Override
    public void onNetWorkDisconn() {
    }

}
